﻿using Microsoft.AspNet.Identity;
using Caltech.Models;
using System.Threading.Tasks;
using System.Web.Http;
using System.Linq;
using AutoMapper;
using System.Collections.Generic;
using CaltechSoft.Service.EntityFW.Entity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Web.Security;
using Caltech.Extensions;
using Caltech.Service.Common;

namespace Caltech.Controllers
{
    
    public class UserController : ApiController
    {
        public UserManager<User> Repository { get; private set; }
        public RoleManager<Role> RoleRepository { get; private set; }

        public UserController(UserManager<User> repository, RoleManager<Role> roleRepository)
        {
            Repository = repository;
            RoleRepository = roleRepository;
        }
        
        public IHttpActionResult Get(Caltech.Service.Common.Roles? role = null, string fullName = null, bool compact = false)
        {
            var query = Repository.Users;

            if (role.HasValue)
            {
                var roleId = RoleRepository.FindByName(role.ToString()).Id;
                query = query.Where(x => x.Roles.Any(y => y.RoleId == roleId));
            }

            if (!string.IsNullOrEmpty(fullName))
            {
                query = query.Where(x => (x.FirstName + " " + x.LastName).ToLower().Contains(fullName.ToLower()));
            }

            if (compact)
            {
                return Ok(Mapper.Map<IEnumerable<UserCompactModel>>(query.ToList()));
            }
            else
            {
                var userModelList = Mapper.Map<IEnumerable<UserSearchModel>>(query.ToList());

                foreach (var item in userModelList)
                {
                    var userRole = RoleRepository.FindById(item.RoleId);

                    if (userRole != null)
	                {
                        item.RoleName = userRole.Name;	 
	                }
                }

                return Ok(userModelList);
            }
        }
        
        public IHttpActionResult Get(string id)
        {
            var entity = Repository.Users.FirstOrDefault(x => x.Id == id);

            var result = Mapper.Map<UserSearchModel>(entity);

            return Ok(result);
        }

        [HasAccess(Areas.User)]
        public async Task<IHttpActionResult> Put(UserSearchModel model)
        {
            var entity = Repository.Users.FirstOrDefault(x => x.Id == model.Id);

            entity.LastName = string.Join(" ", model.FullName.Split(' ').Skip(1));
            entity.FirstName = model.FullName.Split(' ').FirstOrDefault();
            entity.UserName = model.UserName;
            entity.PhoneNumber = model.Mobile;
            entity.Email = model.Email;
            entity.Tel = model.Tel;

            if (model.Activate.HasValue)
            {
                entity.LockoutEnabled = !model.Activate.Value;
            }

            if (!string.IsNullOrEmpty(model.Password))
            {
                await Repository.RemovePasswordAsync(entity.Id);
                await Repository.AddPasswordAsync(entity.Id, model.Password);
            }

            var result = await Repository.UpdateAsync(entity);

            var userRole = entity.Roles.FirstOrDefault();

            if (userRole != null)
	        {
                await Repository.RemoveFromRoleAsync(entity.Id, RoleRepository.FindById(userRole.RoleId).Name);	 
	        }

            await Repository.AddToRoleAsync(entity.Id, model.RoleName);




            return Ok(result);
        }
    }
}